import json
import os
import threading
from datetime import datetime
from tkinter import ttk, Label, scrolledtext, Button, Entry

import pandas as pd
import requests
import tkinter as tk

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.comm.msg_util import msg
from util.comm.path import getConfigPath
from util.window.config_window.config_button import create_config_button


class WinPcYclc():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.elements = []

        self.config_path = getConfigPath()
        self.button = create_config_button(self, True)

        self.menu = ttk.Frame(self.tab)
        self.menu.pack()
        self.elements.append(self.menu)

        config_path = getConfigPath()
        with open(config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        self.menuFrame(self.menu, config)

    def menuFrame(self, tab, config):
        self.menu = tab
        content = config
        params = content["params"]
        # 增加输入框
        map = {}
        if isinstance(params, list):
            row = 1
            for index, param in enumerate(params):
                title = param['field_title']
                field = param['field']
                w = param['width']
                h = param['height']

                # 标题
                self.label = Label(self.menu, text=title)
                self.label.grid(row=row, column=0, padx=5, pady=5)

                self.Entry = Entry(self.menu, width=w)
                self.Entry.grid(row=row, column=1, padx=5, pady=5)
                self.Entry.insert(0, param["field_value"])

                map[field] = self.Entry

                row += 1

                new_row = tk.Frame(self.menu)
                new_row.grid(row=row, column=0, sticky='news')

        # 增加按钮
        button = content["button"]

        self.button = Button(self.menu, text=button, command=lambda n=content["name"], t=tab, c=content, m=map: self.print_entry_sync(n, t, c, m), width=12)
        self.button.grid(row=row, column=1, padx=36, pady=5)

    def print_entry_sync(self, n, t, c, m):
        flag = "sync_flag_%s" % n
        if hasattr(self, flag) and getattr(self, flag) == '1':
            msg('正在处理,请勿重复操作')
            return
        setattr(self, flag, '1')
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=(t, c, m,)),
                  lambda n=n: self.reset_sync(n)).execute_async()

    def reset_sync(self, n):
        flag = "sync_flag_%s" % n
        setattr(self, flag, '0')

    def print_entry(self, t, c, m):
        if hasattr(t, 'label_out'):
            t.label_out.destroy()
        map = {}
        for key, value in m.items():
            v = ""
            try:
                v = value.get()
            except:
                pass
            map[key] = v
        size = map['size']
        name = map['name']
        # 获取服务列表
        total, recs = searchErrRecord(size, name)
        total, res = deleteErrRecord(total, recs)

        createLabelOut(t, "结果：总条数【%s】，执行结果【%s】" % (total, res))


def createLabelOut(tab, message):
    if len(message) > 100:
        message = message[:45] + '...' + message[-45:-1]
    tab.label_out = Label(tab, text=message)
    tab.label_out.grid(column=1)

def searchErrRecord(size, name):
    url = f"https://www.56jzt.com/zuul/flowstatus/findFlow"
    data = "{\"dbflag\":\"*\",\"status\": 2,\"curpage\": 1,\"pagesize\": %s,\"name\":\"%s\",\"sort\":true}" % (size, name)
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.post(url, headers=headers, data=data.encode("utf-8"))

    if response.status_code == 200:
        data = response.json()
        records = data.get("content", [])
        return data.get("totalElements", 0), records
    else:
        print("查询异常记录-请求异常：", response.status_code)
        return 0, "查询异常记录-请求异常：%s" % response.status_code

def deleteErrRecord(totalElements, records):
    if totalElements == 0:
        return 0, "无异常记录"
    ids = []
    for record in records:
        ids.append(record['ID'])
    # 删除异常记录
    url = "https://www.56jzt.com/zuul/flowstatus/flowsremove"
    data = {
              "ids": ids,
              "status": 2,
              "operator": "梅贤军",
              "dbflag": ""
            }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.post(url, headers=headers, data=json.dumps(data).encode("utf-8"))
    if response.status_code == 200:
        data = response.json()
        return totalElements, data.get("msgInfo", "无删除信息")
    else:
        print("删除异常记录-请求异常：", response.status_code)
        return 0, "删除异常记录-请求异常：%s" % response.status_code

